package com.hanxu.controller;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hanxu.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * 不需要使用@ResponseBody 类下面的所有返回的方法都会解析为字符串
 */
@RestController
public class UserController {

    @RequestMapping("/j1/t1")
    //@ResponseBody             //不会走实体解析器 会把当前的返回值变成字符串
    public String json1(){
        User user = new User(1,"含蓄",13);
        return user.toString();
    }

    /**
     * springmvc json提供的方法
     * @return
     */
   // @RequestMapping(value = "/j2/t2",produces = "application/json;charset=utf-8")

    @RequestMapping( "/j2/t2")   //测试配置的springmvc-servlet.xml统一处理乱码
    //@ResponseBody             //不会走实体解析器 会把当前的返回值变成字符串
    public String json2() throws JsonProcessingException {

        //jackson ObjectMapper
        ObjectMapper objectMapper = new ObjectMapper();

        User user = new User(1,"含蓄",13);

        String s = objectMapper.writeValueAsString(user);

        return s;
    }

    /**
     * json 集合返回
     * @return
     * @throws JsonProcessingException
     */
    @RequestMapping( "/j3/t3")   //测试配置的springmvc-servlet.xml统一处理乱码
    public String json3() throws JsonProcessingException {

        //jackson ObjectMapper
        ObjectMapper objectMapper = new ObjectMapper();

        User user1 = new User(1,"含蓄1",11);
        User user2 = new User(2,"含蓄2",12);
        User user3 = new User(3,"含蓄3",13);
        User user4 = new User(4,"含蓄4",14);

        List<User> list = new ArrayList<>();
        list.add(user1);
        list.add(user2);
        list.add(user3);
        list.add(user4);

        String s = objectMapper.writeValueAsString(list);

        return s;
    }

    /**
     * fastjson
     * @return
     */
    @RequestMapping( "/j4/t4")   //测试配置的springmvc-servlet.xml统一处理乱码
    public String json4() {

        User user1 = new User(1,"含蓄1",11);
        User user2 = new User(2,"含蓄2",12);
        User user3 = new User(3,"含蓄3",13);
        User user4 = new User(4,"含蓄4",14);

        List<User> list = new ArrayList<>();
        list.add(user1);
        list.add(user2);
        list.add(user3);
        list.add(user4);


        String s = JSON.toJSONString(list);

        return s;
    }

}
